package com.work.controller;



import com.work.bean.HwStu;
import com.work.bean.Student;
import com.work.bean.User;
import com.work.dao.HwStuAttachDao;
import com.work.dao.HwStuDao;
import com.work.dao.impl.HwStuAttachDaoImpl;
import com.work.dao.impl.HwStuDaoImpl;
import com.work.dto.StudentHw;
import com.work.service.HwStuService;
import com.work.service.impl.HwStuServiceImpl;
import com.work.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;


public class HwStuServlet extends BaseServlet{
    HwStuDao hwStuDao = new HwStuDaoImpl();
    HwStuService hwStuService = new HwStuServiceImpl();
    HwStuAttachDao hwStuAttachDao = new HwStuAttachDaoImpl();
    protected void queryHwStu(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        List<HwStu> hwStus = hwStuDao.queryHwstuByHwId(id);
        req.setAttribute("hwStus",hwStus);
        req.getRequestDispatcher("/pages/teacher/teacher_look.jsp").forward(req,resp);
    }
    protected void queryHwStuById(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        HwStu hwStu = hwStuDao.queryHwstuById(id);
        req.setAttribute("hwStu",hwStu);
        req.getRequestDispatcher("/page/admin/admin_hw.jsp").forward(req,resp);
    }
    protected void saveHwStu(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        String url = null;
        int hw_id = 0;

        if (ServletFileUpload.isMultipartContent(req)) {
            // 创建FileItemFactory 工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            // 创建用于解析上传数据的工具类ServletFileUpload 类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            servletFileUpload.setHeaderEncoding("UTF-8");
            try {
                // 解析上传的数据，得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(req);
                // 循环判断，每一个表单项，是普通类型，还是上传的文件
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        if(fileItem.getFieldName().equals("hw_id")){
                            hw_id = Integer.parseInt(fileItem.getString("UTF-8"));
                        }
                        // 普通表单项
                        System.out.println("表单项的name 属性值：" + fileItem.getFieldName());
                        // 参数UTF-8.解决乱码问题
                        System.out.println("表单项的value 属性值：" + fileItem.getString("UTF-8"));
                    } else {
                        // 上传的文件
                        System.out.println("表单项的name 属性值：" + fileItem.getFieldName());
                        System.out.println("上传的文件名：" + fileItem.getName());
                        url = fileItem.getName();
                        fileItem.write(new File("d:\\work\\student\\" + fileItem.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Student student = (Student) req.getSession().getAttribute("student");
        hwStuService.saveHwStu(new HwStu(null,hw_id,student.getId(),"0"),url);
        req.setAttribute("err","上传成功");
        req.getRequestDispatcher("/pages/student/student_submit.jsp").forward(req, resp);

    }
    protected void updateHwStu(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        String status = req.getParameter("status");
        HwStu hwStu = new HwStu(id,null,null,status);
        hwStuDao.update(hwStu);
        int hw_id = hwStuDao.queryHwstuById(id).getHw_id();
        resp.sendRedirect(req.getContextPath() + "/HwStuServlet?action=queryStudentHw&id="+hw_id);
    }
    protected void deleteHwStu(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        int hw_id = WebUtils.parseInt(req.getParameter("hw_id"),0);
        hwStuDao.deleteHwstu(id);
        hwStuAttachDao.deleteHwStuAttach1(id);
        resp.sendRedirect(req.getContextPath() + "/HwStuServlet?action=queryStudentHw&id="+hw_id);
    }
    protected void queryStudentHw(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        List<StudentHw> list = hwStuService.query(id);
        req.setAttribute("studentHw", list);
        if(((User) req.getSession().getAttribute("user")).getType().equals("1")) {
            req.getRequestDispatcher("/pages/teacher/teacher_look.jsp").forward(req, resp);
        }else{
            req.getRequestDispatcher("/pages/admin/materrial/admin_materrial_student.jsp").forward(req, resp);

        }
    }
    protected void downloadStuHw(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        System.out.println(id);
        String url = hwStuAttachDao.queryHwStuAttachById(id).getUrl();
        String fileName=new String(url.getBytes("iso8859-1"), "UTF-8");
        // 上传的文件都是保存在/WEB-INF/upload目录下的子目录当中
        String fileSaveRootPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        // 得到要下载的文件
        File file = new File("D:\\work\\student\\" + url);
        // 如果文件不存在
        if (!file.exists()) {
            req.setAttribute("message", "您要下载的资源已被删除！！");
            req.getRequestDispatcher("/pages/student/student_download.jsp").forward(req, resp);
            return;
        }
        // 设置响应头，控制浏览器下载该文件
        // 设置文件MIME类型
        resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(url, "UTF-8"));
        FileInputStream in = new FileInputStream(file);
        OutputStream out = resp.getOutputStream();
        byte buffer[] = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        in.close();
        out.close();
    }
}
